from counterpoint.exceptions import Http403
from counterpoint.helpers import get_forum_user
from django.http import HttpResponseForbidden
from django.template import loader, RequestContext


try:
    import tidy
    use_tidy = True
except:
    use_tidy = False


class HttpErrorMiddleware(object):
    """
    Catches HTTP errors that are not handled in django already.

    Supported exceptions:

      * counterpoint.exceptions.Http403
    """

    def process_exception(self, request, exception):
        if isinstance(exception, Http403):
            t = loader.get_template('403.html')
            c = RequestContext(request, {'message': exception.message})
            return HttpResponseForbidden(t.render(c))


class CounterPointMiddleware(object):
    """Adds the ForumUser for the current user to request."""

    def process_request(self, request):
        request.forum_user = get_forum_user(request.user)
        return None


class PrettifyMiddleware(object):
    """Runs HTML output through tidy."""

    options = dict(output_xhtml=True,
                   indent=True,
                   tidy_mark=False,
                   hide_comments=True,
                   input_encoding='utf8',
                   wrap=120)

    def process_response(self, request, response):
        content_type = response['content-type'].split(';', 1)[0]
        if use_tidy and content_type in ['text/html']:
            content = response.content
            content = str(tidy.parseString(content, **self.options))
            response.content = content
        return response
